package com.sanery.ui.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sanery.entity.Link;
import com.sanery.entity.User;
import com.sanery.service.LinkService;

@Controller
public class LinkController {

	@Autowired
	@Qualifier("lkservice")
	private LinkService lkservice;

	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(HttpSession session, Model m) {
		User user = (User) session.getAttribute("user");
		Integer id = user.getId();
		List<Link> links = lkservice.getMyLink(id);
		m.addAttribute("links", links);
		return "/index";
	}

	@RequestMapping(value = "/del")
	public String del(Integer id, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Integer userId = user.getId();
		lkservice.delLink(id, userId);
		return "redirect:/index";
	}

	@RequestMapping(value = "/sort")
	public String sort() {
		return "/sort";
	}

	@RequestMapping(value = "/getSort")
	@ResponseBody
	public Map<String, List<Link>> getSort(HttpSession session) {
		User user = (User) session.getAttribute("user");
		Integer id = user.getId();
		List<Link> relatives = lkservice.getSortLink("亲人", id);
		List<Link> colleague = lkservice.getSortLink("同事", id);
		List<Link> classmate = lkservice.getSortLink("同学", id);
		List<Link> friend = lkservice.getSortLink("朋友", id);
		Map<String, List<Link>> map = new HashMap<String, List<Link>>();
		map.put("亲人", relatives);
		map.put("同事", colleague);
		map.put("同学", classmate);
		map.put("朋友", friend);
		return map;
	}

	@RequestMapping(value = "/change")
	public String change(Integer linkId, String name, Integer type, String phone, String email, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Integer userId = user.getId();

		name = name.trim();
		phone = phone.trim();
		email = email.trim();

		if (linkId == null) {
			// 新增
			lkservice.createLink(name, type, phone, email, userId);
		} else {
			// 修改
			lkservice.changeLink(linkId, name, type, phone, email, userId);
		}

		return "redirect:/index";
	}

	@RequestMapping(value = "/searchLink", method = RequestMethod.POST)
	@ResponseBody
	public List<Link> searchLink(String val, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Integer userId = user.getId();
		val = "%" + val + "%";
		List<Link> list = lkservice.searchLink(val, userId);
		return list;
	}
}
